// pages/order-manage/order-manage.js
const app = getApp()
const { request } = require("../../utils/request")

Page({
  data: {
    currentTab: "all",
    orderList: [],
    statusMap: {
      2: "待发货",
      4: "已完成",
    },
  },

  onLoad() {
    this.fetchOrderList()
  },

  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ currentTab: tab }, () => {
      // 在状态更新后再获取订单列表
      this.fetchOrderList()
    })
  },

  // 获取订单列表
  fetchOrderList() {
    let status = null

    // 根据当前标签设置状态
    switch (this.data.currentTab) {
      case "pending":
        status = [2]
        break
      case "completed":
        status = [4]
        break
      default:
        status = [2, 4]
    }

    wx.showLoading({
      title: "加载中",
    })

    request({
      url: `${app.globalData.baseUrl}/admin/order/getOrderList4Manage${status ? "?status=" + status.join(",") : ""}`,
      method: "GET",
    })
      .then((res) => {
        wx.hideLoading()
        if (res.data.code === 1 && res.data.data) {
          // 为每个订单计算总积分并添加到订单对象中
          const orderList = res.data.data.map((order) => {
            // 计算总积分
            const totalPrice = this.getTotalPrice(order.orderDetailVoList || [])
            // 将总积分添加到订单对象
            return {
              ...order,
              totalPrice: totalPrice,
            }
          })

          this.setData({
            orderList: orderList,
          })
        } else {
          this.setData({
            orderList: [],
          })
          wx.showToast({
            title: res.data.msg || "暂无订单数据",
            icon: "none",
          })
        }
      })
      .catch((err) => {
        wx.hideLoading()
        console.error("请求失败:", err)
        wx.showToast({
          title: "网络请求失败",
          icon: "none",
        })
        this.setData({
          orderList: [],
        })
      })
  },

  // 计算订单总积分
  getTotalPrice(orderDetails) {
    if (!orderDetails || orderDetails.length === 0) return 0
    return orderDetails.reduce((total, item) => {
      return total + item.price * item.count
    }, 0)
  },

  // 完成订单
  completeOrder(e) {
    const orderId = e.currentTarget.dataset.id
    const totalPoint = e.currentTarget.dataset.total

    wx.showModal({
      title: "确认完成",
      content: "是否确认完成该订单？",
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: "处理中" })
          request({
            url: `${app.globalData.baseUrl}/admin/order/completed?id=${orderId}&totalPoint=${totalPoint}`,
            method: "PUT",
          })
            .then((res) => {
              wx.hideLoading()
              if (res.data.code === 1) {
                wx.showToast({
                  title: "操作成功",
                  icon: "success",
                })
                this.fetchOrderList()
              } else {
                wx.showToast({
                  title: res.data.msg || "操作失败",
                  icon: "none",
                })
              }
            })
            .catch(() => {
              wx.hideLoading()
              wx.showToast({
                title: "网络请求失败",
                icon: "none",
              })
            })
        }
      },
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.fetchOrderList()
    wx.stopPullDownRefresh()
  },
})
